import 'dart:convert';

import 'package:common_utils/common_utils.dart';
import 'package:get/get.dart';
import 'package:psi/base/base_controller.dart';
import 'package:psi/entity/response/add_sales_resp.dart';
import 'package:psi/entity/response/sales_item_resp.dart';
import 'package:psi/entity/sales_entity.dart';

import '../../../../entity/common_resp.dart';
import '../../../../entity/response/recent_names_list_resp.dart';
import '../../../../http/api_service.dart';
import 'sales_add_state.dart';

class SalesAddLogic extends BaseController {
  final SalesAddState state = SalesAddState();

  @override
  void onReady() async {
    // TODO: implement onReady
    super.onReady();
    if (Get.arguments["type"] != null) {
      state.type = Get.arguments["type"];
      if (state.type == SalesType.add) {
        state.isEdit.value = true;
      }
    }
    if (Get.arguments["data"] != null) {
      state.sales.value = Get.arguments["data"];
    }
    update(["all"]);
    await getRecentNames();
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
  }


  void addAction() {
    state.sales.value.itemList!.add(SalesItem());
    update(["item"]);
  }

  void deleteAction(SalesItem item) {
    state.sales.value.itemList!.remove(item);
    update(["item", "amount"]);
  }

  Future<void> getRecentNames({int? count}) async {
    try {
      if (count != null) {
        state.count.value = count;
      }
      RecentNamesListResp resp = await ApiService.request.recentNames(count: state.count.value);
      if (resp.code == 0) {
        state.recentNames.value = resp.data ?? [];
        update(["itemRecentNames"]);
      }
    } catch(e) {
      LogUtil.e(e);
    }
  }

  Future<void> clickAction() async {

    if (state.type == SalesType.add) {
      await doneAction();
    } else {
      if (state.isEdit.value) {
        await updateAction();
      }
    }
  }

  Future<void> updateAction() async {
    showLoading();
    try {
      SalesItemResp resp = await ApiService.request.editSales(state.sales.value);
      hideLoading();
      if (resp.code == 0) {
        state.isEdit.value = !state.isEdit.value;
        goBack(result: resp.data);
      } else {
        showToast(resp.message);
      }
    } catch(e) {
      hideLoading();
      showToast("服务器连接失败，请稍后再试");
    }
  }

  Future<void> doneAction() async {
    try {
      showLoading();
      AddSalesResp resp = await ApiService.request.addSales(state.sales.value);
      hideLoading();
      if (resp.code == 0) {
        goBack(result: resp.data);
      } else {
        showToast(resp.message);
      }
    } catch(e) {
      hideLoading();
      showToast("服务器连接失败，请稍后再试");
      LogUtil.e(e);
    }
  }
}
